﻿using UnityEngine;
using System.Collections.Generic;

public class ObjectPool {

    private int poolSize = 10;
    private bool canGrow = false;

    private List<GameObject> pool = new List<GameObject>();
    GameObject parentObj;

    public void Create(GameObject objectToPool)
    {
        parentObj = new GameObject(objectToPool.name);

        pool = new List<GameObject>(poolSize);

        for (int f = 0; f < poolSize; f++)
        {
            GameObject obj = (GameObject)GameObject.Instantiate(objectToPool);
            obj.SetActive(false);
            obj.transform.parent = parentObj.transform;
            pool.Add(obj);
        }
    }

    public ObjectPool(int _poolSize = 10, bool _canGrow = false)
    {
        poolSize = _poolSize;
        canGrow = _canGrow;
    }

    ~ObjectPool()
    {
        Destroy();
    }

    public void Destroy()
    {
        pool.Clear();
    }

    public GameObject Spawn(GameObject objectToSpawn)
    {
        if (pool.Count == 0)
            Create(objectToSpawn);

        for (int f = 0; f < pool.Count; f++)
        {
            if (!pool[f].activeInHierarchy)
            {
                pool[f].SetActive(true);
                return pool[f];
            }
        }

        if (canGrow)
        {
            GameObject obj = (GameObject)GameObject.Instantiate(objectToSpawn);
            obj.SetActive(true);
            obj.transform.parent = parentObj.transform;
            pool.Add(obj);
            return pool[pool.Count - 1];
        }

        return null;
    }

    public void Despawn(GameObject objectToDespawn)
    {
        objectToDespawn.SetActive(false);
    }
}
